<template>
  <div class="logs-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>系统日志</h3>
          <div class="header-actions">
            <el-button type="primary" @click="refreshLogs">
              <el-icon><Refresh /></el-icon>
              刷新日志
            </el-button>
            <el-button type="success" @click="exportLogs">
              <el-icon><Download /></el-icon>
              导出日志
            </el-button>
            <el-button type="warning" @click="clearLogs">
              <el-icon><Delete /></el-icon>
              清空日志
            </el-button>
          </div>
        </div>
      </template>

      <!-- 日志类型标签页 -->
      <el-tabs v-model="activeLogType" @tab-change="handleLogTypeChange">
        <el-tab-pane label="操作日志" name="operation">
          <div class="log-content">
            <!-- 搜索区域 -->
            <div class="search-area">
              <el-form :model="searchForm" inline>
                <el-form-item label="用户">
                  <el-input v-model="searchForm.user" placeholder="请输入用户名" clearable />
                </el-form-item>
                <el-form-item label="操作类型">
                  <el-select v-model="searchForm.operation" placeholder="请选择操作类型" clearable>
                    <el-option label="登录" value="login" />
                    <el-option label="登出" value="logout" />
                    <el-option label="新增" value="create" />
                    <el-option label="编辑" value="update" />
                    <el-option label="删除" value="delete" />
                    <el-option label="查询" value="query" />
                    <el-option label="导出" value="export" />
                    <el-option label="导入" value="import" />
                  </el-select>
                </el-form-item>
                <el-form-item label="模块">
                  <el-select v-model="searchForm.module" placeholder="请选择模块" clearable>
                    <el-option label="用户管理" value="user" />
                    <el-option label="角色管理" value="role" />
                    <el-option label="商品管理" value="product" />
                    <el-option label="订单管理" value="order" />
                    <el-option label="库存管理" value="inventory" />
                    <el-option label="财务管理" value="finance" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="searchForm.dateRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="handleReset">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 操作日志表格 -->
            <el-table :data="operationLogs" v-loading="loading" stripe>
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="user" label="用户" width="120" />
              <el-table-column prop="operation" label="操作类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="getOperationType(row.operation)">
                    {{ getOperationText(row.operation) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="module" label="模块" width="120" />
              <el-table-column prop="description" label="操作描述" min-width="200" />
              <el-table-column prop="ip" label="IP地址" width="130" />
              <el-table-column prop="userAgent" label="用户代理" width="200" show-overflow-tooltip />
              <el-table-column prop="result" label="结果" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.result === '成功' ? 'success' : 'danger'">
                    {{ row.result }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="操作时间" width="180" />
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewLogDetail(row)">
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="登录日志" name="login">
          <div class="log-content">
            <!-- 搜索区域 -->
            <div class="search-area">
              <el-form :model="loginSearchForm" inline>
                <el-form-item label="用户名">
                  <el-input v-model="loginSearchForm.username" placeholder="请输入用户名" clearable />
                </el-form-item>
                <el-form-item label="登录状态">
                  <el-select v-model="loginSearchForm.status" placeholder="请选择登录状态" clearable>
                    <el-option label="成功" value="success" />
                    <el-option label="失败" value="failed" />
                  </el-select>
                </el-form-item>
                <el-form-item label="IP地址">
                  <el-input v-model="loginSearchForm.ip" placeholder="请输入IP地址" clearable />
                </el-form-item>
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="loginSearchForm.dateRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleLoginSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="handleLoginReset">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 登录日志表格 -->
            <el-table :data="loginLogs" v-loading="loading" stripe>
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户名" width="120" />
              <el-table-column prop="status" label="登录状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                    {{ row.status === 'success' ? '成功' : '失败' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="ip" label="IP地址" width="130" />
              <el-table-column prop="location" label="登录地点" width="150" />
              <el-table-column prop="userAgent" label="用户代理" width="200" show-overflow-tooltip />
              <el-table-column prop="failureReason" label="失败原因" width="150" />
              <el-table-column prop="loginTime" label="登录时间" width="180" />
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="loginPagination.currentPage"
                v-model:page-size="loginPagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="loginPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleLoginSizeChange"
                @current-change="handleLoginCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="系统日志" name="system">
          <div class="log-content">
            <!-- 搜索区域 -->
            <div class="search-area">
              <el-form :model="systemSearchForm" inline>
                <el-form-item label="日志级别">
                  <el-select v-model="systemSearchForm.level" placeholder="请选择日志级别" clearable>
                    <el-option label="DEBUG" value="debug" />
                    <el-option label="INFO" value="info" />
                    <el-option label="WARN" value="warn" />
                    <el-option label="ERROR" value="error" />
                    <el-option label="FATAL" value="fatal" />
                  </el-select>
                </el-form-item>
                <el-form-item label="模块">
                  <el-input v-model="systemSearchForm.module" placeholder="请输入模块名称" clearable />
                </el-form-item>
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="systemSearchForm.dateRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSystemSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="handleSystemReset">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 系统日志表格 -->
            <el-table :data="systemLogs" v-loading="loading" stripe>
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="level" label="级别" width="100">
                <template #default="{ row }">
                  <el-tag :type="getLogLevelType(row.level)">
                    {{ row.level.toUpperCase() }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="module" label="模块" width="150" />
              <el-table-column prop="message" label="日志信息" min-width="300" />
              <el-table-column prop="createTime" label="时间" width="180" />
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewSystemLogDetail(row)">
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="systemPagination.currentPage"
                v-model:page-size="systemPagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="systemPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSystemSizeChange"
                @current-change="handleSystemCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="logDetailVisible"
      title="日志详情"
      width="800px"
    >
      <div v-if="currentLog">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ currentLog.user }}</el-descriptions-item>
          <el-descriptions-item label="操作类型">
            <el-tag :type="getOperationType(currentLog.operation)">
              {{ getOperationText(currentLog.operation) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="模块">{{ currentLog.module }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
          <el-descriptions-item label="结果">
            <el-tag :type="currentLog.result === '成功' ? 'success' : 'danger'">
              {{ currentLog.result }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作时间">{{ currentLog.createTime }}</el-descriptions-item>
          <el-descriptions-item label="用户代理">{{ currentLog.userAgent }}</el-descriptions-item>
          <el-descriptions-item label="操作描述" :span="2">{{ currentLog.description }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider>请求参数</el-divider>
        <pre class="log-detail-content">{{ currentLog.requestParams }}</pre>
        
        <el-divider>响应结果</el-divider>
        <pre class="log-detail-content">{{ currentLog.responseResult }}</pre>
      </div>
    </el-dialog>

    <!-- 系统日志详情对话框 -->
    <el-dialog
      v-model="systemLogDetailVisible"
      title="系统日志详情"
      width="800px"
    >
      <div v-if="currentSystemLog">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentSystemLog.id }}</el-descriptions-item>
          <el-descriptions-item label="级别">
            <el-tag :type="getLogLevelType(currentSystemLog.level)">
              {{ currentSystemLog.level.toUpperCase() }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="模块">{{ currentSystemLog.module }}</el-descriptions-item>
          <el-descriptions-item label="时间">{{ currentSystemLog.createTime }}</el-descriptions-item>
          <el-descriptions-item label="日志信息" :span="2">{{ currentSystemLog.message }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider>堆栈信息</el-divider>
        <pre class="log-detail-content">{{ currentSystemLog.stack }}</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const activeLogType = ref('operation')
const loading = ref(false)
const logDetailVisible = ref(false)
const systemLogDetailVisible = ref(false)
const currentLog = ref(null)
const currentSystemLog = ref(null)

// 操作日志搜索表单
const searchForm = reactive({
  user: '',
  operation: '',
  module: '',
  dateRange: []
})

// 登录日志搜索表单
const loginSearchForm = reactive({
  username: '',
  status: '',
  ip: '',
  dateRange: []
})

// 系统日志搜索表单
const systemSearchForm = reactive({
  level: '',
  module: '',
  dateRange: []
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const loginPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const systemPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 操作日志数据
const operationLogs = ref([
  {
    id: 1,
    user: 'admin',
    operation: 'login',
    module: '用户管理',
    description: '用户登录系统',
    ip: '192.168.1.100',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    result: '成功',
    createTime: '2024-01-15 10:00:00',
    requestParams: '{"username": "admin", "password": "***"}',
    responseResult: '{"code": 200, "message": "登录成功"}'
  },
  {
    id: 2,
    user: 'admin',
    operation: 'create',
    module: '用户管理',
    description: '新增用户：张三',
    ip: '192.168.1.100',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    result: '成功',
    createTime: '2024-01-15 10:05:00',
    requestParams: '{"name": "张三", "email": "zhangsan@example.com"}',
    responseResult: '{"code": 200, "message": "用户创建成功"}'
  },
  {
    id: 3,
    user: 'admin',
    operation: 'update',
    module: '商品管理',
    description: '编辑商品：iPhone 15',
    ip: '192.168.1.100',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    result: '成功',
    createTime: '2024-01-15 10:10:00',
    requestParams: '{"id": 1, "name": "iPhone 15", "price": 5999}',
    responseResult: '{"code": 200, "message": "商品更新成功"}'
  }
])

// 登录日志数据
const loginLogs = ref([
  {
    id: 1,
    username: 'admin',
    status: 'success',
    ip: '192.168.1.100',
    location: '北京市',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    failureReason: '',
    loginTime: '2024-01-15 10:00:00'
  },
  {
    id: 2,
    username: 'test',
    status: 'failed',
    ip: '192.168.1.101',
    location: '上海市',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    failureReason: '密码错误',
    loginTime: '2024-01-15 09:55:00'
  }
])

// 系统日志数据
const systemLogs = ref([
  {
    id: 1,
    level: 'info',
    module: 'UserService',
    message: '用户登录成功',
    createTime: '2024-01-15 10:00:00',
    stack: ''
  },
  {
    id: 2,
    level: 'warn',
    module: 'DatabaseService',
    message: '数据库连接池使用率过高',
    createTime: '2024-01-15 09:55:00',
    stack: 'Warning: Connection pool usage above 80%\n    at DatabaseService.checkPool (database.js:45)'
  },
  {
    id: 3,
    level: 'error',
    module: 'OrderService',
    message: '订单创建失败',
    createTime: '2024-01-15 09:50:00',
    stack: 'Error: Order creation failed\n    at OrderService.createOrder (order.js:123)\n    at async OrderController.create (order.js:45)'
  }
])

// 方法
const handleLogTypeChange = (type) => {
  activeLogType.value = type
  loadLogs()
}

const loadLogs = () => {
  loading.value = true
  setTimeout(() => {
    if (activeLogType.value === 'operation') {
      pagination.total = operationLogs.value.length
    } else if (activeLogType.value === 'login') {
      loginPagination.total = loginLogs.value.length
    } else if (activeLogType.value === 'system') {
      systemPagination.total = systemLogs.value.length
    }
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadLogs()
}

const handleReset = () => {
  Object.assign(searchForm, {
    user: '',
    operation: '',
    module: '',
    dateRange: []
  })
  handleSearch()
}

const handleLoginSearch = () => {
  loginPagination.currentPage = 1
  loadLogs()
}

const handleLoginReset = () => {
  Object.assign(loginSearchForm, {
    username: '',
    status: '',
    ip: '',
    dateRange: []
  })
  handleLoginSearch()
}

const handleSystemSearch = () => {
  systemPagination.currentPage = 1
  loadLogs()
}

const handleSystemReset = () => {
  Object.assign(systemSearchForm, {
    level: '',
    module: '',
    dateRange: []
  })
  handleSystemSearch()
}

const viewLogDetail = (log) => {
  currentLog.value = log
  logDetailVisible.value = true
}

const viewSystemLogDetail = (log) => {
  currentSystemLog.value = log
  systemLogDetailVisible.value = true
}

const getOperationType = (operation) => {
  const typeMap = {
    login: 'success',
    logout: 'info',
    create: 'primary',
    update: 'warning',
    delete: 'danger',
    query: 'info',
    export: 'success',
    import: 'primary'
  }
  return typeMap[operation] || 'info'
}

const getOperationText = (operation) => {
  const textMap = {
    login: '登录',
    logout: '登出',
    create: '新增',
    update: '编辑',
    delete: '删除',
    query: '查询',
    export: '导出',
    import: '导入'
  }
  return textMap[operation] || operation
}

const getLogLevelType = (level) => {
  const typeMap = {
    debug: 'info',
    info: 'primary',
    warn: 'warning',
    error: 'danger',
    fatal: 'danger'
  }
  return typeMap[level] || 'info'
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadLogs()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadLogs()
}

const handleLoginSizeChange = (size) => {
  loginPagination.pageSize = size
  loadLogs()
}

const handleLoginCurrentChange = (page) => {
  loginPagination.currentPage = page
  loadLogs()
}

const handleSystemSizeChange = (size) => {
  systemPagination.pageSize = size
  loadLogs()
}

const handleSystemCurrentChange = (page) => {
  systemPagination.currentPage = page
  loadLogs()
}

const refreshLogs = () => {
  loadLogs()
  ElMessage.success('日志已刷新')
}

const exportLogs = () => {
  ElMessage.success('日志导出成功')
}

const clearLogs = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有日志吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    if (activeLogType.value === 'operation') {
      operationLogs.value = []
    } else if (activeLogType.value === 'login') {
      loginLogs.value = []
    } else if (activeLogType.value === 'system') {
      systemLogs.value = []
    }
    
    ElMessage.success('日志清空成功')
    loadLogs()
  } catch {
    // 用户取消操作
  }
}

// 生命周期
onMounted(() => {
  loadLogs()
})
</script>

<style scoped>
.logs-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.log-content {
  padding: 0;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.log-detail-content {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #333;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 300px;
  overflow-y: auto;
}
</style>
